#!/usr/bin/env perl
# Original python script Copyright (C) 2009  Glen Pitt-Pladdy
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

use LWP::Simple;

$CACHETIME = 30;
$CACHEFILE = '/tmp/snmp-cache-apache';

# check for cache file newer CACHETIME seconds ago
if ( -f $CACHEFILE && time - (stat( $CACHEFILE ))[9] < $CACHETIME) {
        # use cached data
#print "Using cached data from file $CACHEFILE.\n";
        open (INFILE, "<$CACHEFILE" )
                or die "File open failure: $CACHEFILE\n";
        @data = <INFILE>;
        close INFILE;
} else {
        # grab the status URL (fresh data)
        @data = split /(\n)/, LWP::Simple::get( 'http://localhost/server-status?auto' )
                or die "Data fetch failure.\n";

        # write file
        $tmpfile = "$CACHEFILE.TMP.$PID";
        open (OUTFILE, ">$tmpfile")
                or die "File open failure: $tmpfile\n";
        print OUTFILE @data;
        close OUTFILE;
        rename ( $tmpfile, $CACHEFILE );
}

# dice up the data
@scoreboardkey = ( '_', 'S', 'R', 'W', 'K', 'D', 'C', 'L', 'G', 'I', '.' );
%params = {};
foreach $line (@data) {
        chomp $line;
        @fields = split( /: /, $line);
        if ($fields[0] eq 'Scoreboard') {
                # count up the scoreboard into states
                %states = {};
                foreach $state (@scoreboardkey) {
                        $states{$state} = 0;
                }
                foreach $state ( split(//, $fields[1]) ) {
                        $states{$state}++;
                }
        } elsif ($fields[0] eq 'Total kBytes') {
                # turn into base (byte) value
                $params{$fields[0]} = int($fields[1])*1024;
        } else {
                # just store everything else
                $params{$fields[0]} = $fields[1];
        }
}

# output the data in order (this is because some platforms don't have them all)
@dataorder = (
        'Total Accesses',
        'Total kBytes',
        'CPULoad',
        'Uptime',
        'ReqPerSec',
        'BytesPerSec',
        'BytesPerReq',
        'BusyServers',
        'IdleServers'
);
foreach $param (@dataorder) {
        if (exists $params{$param}) {
                print $params{$param}."\n";
        } else {
                # not all Apache's have all stats
                print "U\n";
        }
}

# print the scoreboard
foreach $state (@scoreboardkey) {
        print $states{$state}."\n";
}
